package active

import (
	"fmt"
	"server/game/cache"
	"server/share/config"
	"strconv"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosgo/slice"
	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

func init() {
	Register(&MonthSign{})
}

type MonthSign struct {
	Days  []int32 ` json:"days" bson:"days"`
	Total []int32 ` json:"total" bson:"total"` //累计签到奖励
}

func (this *MonthSign) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*MonthSign, *context.Context) interface{})
	return f(this, handle)
}

// Submit 新版月签到
//
// id 活动id,参考活动总控中的列表
//
// key monthGift.id

func (this *MonthSign) Submit(c *context.Context) interface{} {
	id := c.GetInt32("id")
	key := c.GetInt32("key")
	if key <= 0 {
		return errors.ErrArgEmpty
	}
	ac := config.Data.Active[id]
	if ac == nil {
		return errors.ErrConfigEmpty
	}
	if ac.Mod != config.Data.ActiveMod.MonthSign {
		return c.Errorf(0, "active config mod mismatched")
	}

	rc := config.Data.MonthSign[key]
	if rc == nil {
		return errors.ErrConfigEmpty
	}

	daily := times.Daily(0)
	now := daily.Format("102")
	if now != fmt.Sprintf("%d", key) {
		return c.Errorf(0, "无法补签")
	}

	handle := cache.GetActive(c.Player.Updater)
	item, _, err := handle.Verify(id)
	if err != nil {
		return err
	}

	att := &MonthSign{}
	if err = item.Unmarshal(att); err != nil {
		return err
	}
	if slice.Has(att.Days, key) {
		return c.Errorf(0, "这天已经签到过了")
	}
	att.Days = append(att.Days, key)
	c.Player.Add(rc.Gift, rc.Amount)
	handle.SetAttach(item.OID, att)
	//判断累计签到
	ms := daily.Format("1")
	mi, _ := strconv.Atoi(ms)
	ds := config.GetMonthSignDayCountReward(int32(mi))
	tc := int32(len(att.Days))
	for _, v := range ds {
		if tc >= v.Times && !slice.Has(att.Total, v.Id) {
			att.Total = append(att.Total, v.Id)
			c.Player.Add(v.Gift, v.Amount)
		}
	}

	//判断今日运势
	var rateGift int32
	dom := config.GetActiveRandom()
	if rdm := dom.MonthSignRateGift[rc.Group]; rdm != nil {
		rateGift = rdm.Roll()
	}
	if rateGift > 0 {
		rgc := config.Data.MonthSignRateGift[rateGift]
		if rgc.Gift > 0 {
			c.Player.Add(rgc.Gift, 1)
		}
	}

	c.Player.Emit(config.Data.Events.MonthSign, 1)
	return rateGift
}

/**
 * @name monthGift
 * @param int id 月签到表里的id
 * 月签到
 */

func (this *MonthSign) MonthGift(c *context.Context) interface{} {
	return c.Error("已经废弃，请使用月卡功能")
}

/**
 * @name monthCardGift
 * @param string id 用户唯一ID
 * 月卡签到奖励
 */

func (this *MonthSign) MonthCardGift(c *context.Context) interface{} {
	return c.Error("已经废弃，请使用月卡功能")
}
